import { defineStore } from 'pinia'
import { userInformation } from '@api/userApi'
import { useMainStore } from '@/store'
import router from '@/router'

export const useUserStore = defineStore('user-store', {
  state: () => {
    return {
      token: localStorage.getItem('token') || null,
      role: null
    }
  },
  getters: {
    getUserAuth(state) {
      return state.role === 'admin'
    },
    isLogin(state) {
      return Boolean(state.token)
    }
  },
  actions: {
    setUserState(info) {
      const { token, role } = info
      const _token = 'Bearer ' + token
      localStorage.setItem('token', _token)
      this.$patch({
        token: _token,
        role: role
      })
    },
    async getUserInfo() {
      const that = this
      useMainStore().setPageLoading(true)
      return new Promise((resolve, reject) => {
        userInformation().then(res => {
          if (res?.statusCode !== 200) return false
          that.$patch({ role: res.data.role })
          resolve(res)
        }).catch(err => {
          reject(err)
          that.logout()
        }).finally(() => {
          useMainStore().setPageLoading(false)
        })
      })
    },
    logout() {
      localStorage.removeItem('token')
      this.$patch({ token: '' })
      router.replace('/').finally(() => {
        $message.destroyAll()
        location.reload()
      })
    },
  },
})
